package com.lijian.community.controller;

import com.lijian.community.dto.AccessTokenDTO;
import com.lijian.community.dto.GithubUser;
import com.lijian.community.mapper.UserMapper;
import com.lijian.community.model.User;
import com.lijian.community.provider.GithubProvider;
import com.lijian.community.service.UserService;
import com.lijian.community.utils.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class AuthorizeController {

    @Autowired
    private GithubProvider githubProvider;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    @Value("${github.client.id}")
    private String clientId;

    @Value("${github.client.secret}")
    private String clientSecret;

    @Value("${github.redirect.uri}")
    private String redirectUri;

    @GetMapping("/callback")
    public String callback(@RequestParam(name = "code") String code,
                           @RequestParam(name = "state") String state,
                           HttpServletResponse response) {
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        accessTokenDTO.setCode(code);
        accessTokenDTO.setRedirect_uri(redirectUri);
        accessTokenDTO.setClient_id(clientId);
        accessTokenDTO.setClient_secret(clientSecret);
        accessTokenDTO.setState(state);
        String accessToken = githubProvider.getAccessToken(accessTokenDTO);
        GithubUser githubUser = githubProvider.getUser(accessToken);
        if(githubUser == null && githubUser.getId() == null){
            //登陆失败，重新登陆
            return "redirect:/";
        }
        //登陆成功。写cookie 和 session
        User user = new User();
        //生成token
        String token = UUID.randomUUID().toString();
        user.setToken(token);
        user.setName(githubUser.getName());
        user.setAccountId(String.valueOf(githubUser.getId()));

        user.setPortraitUrl(githubUser.getAvatarUrl());
        //登陆成功，写入数据库，如果用户已经写入过数据库 做更新操作，更新token
        userService.insertOrUpdate(user);
        //写入cookie
        response.addCookie(new Cookie("token", token));
        //redirect重定向到根路径，去掉地址栏
        return "redirect:/";

    }
    @GetMapping("/logout")
    public String logout(HttpServletRequest request,
                         HttpServletResponse response){
        //删除session
        request.getSession().removeAttribute("user");

        //删除token
        //可以通过重新创建一个重名的cookie来覆盖
        Cookie cookie = new Cookie("token", null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/";
    }
}
